<template>
  <div class="order-detail">
    <div v-if="!orderInfo" class="loading">
      <el-skeleton :rows="10" animated />
    </div>
    
    <div v-else class="order-content">
      <el-card class="order-card">
        <div slot="header" class="order-header">
          <span>订单详情</span>
          <el-tag :type="getStatusType(orderInfo.status)">{{ getStatusText(orderInfo.status) }}</el-tag>
        </div>
        
        <div class="order-info">
          <div class="info-item">
            <span class="label">订单编号：</span>
            <span class="value">{{ orderInfo.id }}</span>
          </div>
          <div class="info-item">
            <span class="label">下单时间：</span>
            <span class="value">{{ formatDate(orderInfo.createTime) }}</span>
          </div>
          <div v-if="orderInfo.deliveryTime" class="info-item">
            <span class="label">配送时间：</span>
            <span class="value">{{ formatDate(orderInfo.deliveryTime) }}</span>
          </div>
          <div v-if="orderInfo.completeTime" class="info-item">
            <span class="label">完成时间：</span>
            <span class="value">{{ formatDate(orderInfo.completeTime) }}</span>
          </div>
        </div>
      </el-card>
      
      <el-card class="merchant-card">
        <div slot="header" class="merchant-header">
          <span>商家信息</span>
        </div>
        
        <div class="merchant-info">
          <div class="info-item">
            <span class="label">商家名称：</span>
            <span class="value">{{ orderInfo.merchantName }}</span>
          </div>
          <div class="info-item">
            <span class="label">联系电话：</span>
            <span class="value">{{ orderInfo.merchantPhone }}</span>
          </div>
        </div>
      </el-card>
      
      <el-card class="delivery-card">
        <div slot="header" class="delivery-header">
          <span>配送信息</span>
        </div>
        
        <div class="delivery-info">
          <div class="info-item">
            <span class="label">收货地址：</span>
            <span class="value">{{ orderInfo.address }}</span>
          </div>
          <div class="info-item">
            <span class="label">联系电话：</span>
            <span class="value">{{ orderInfo.phone }}</span>
          </div>
          <div v-if="orderInfo.rider" class="info-item">
            <span class="label">配送骑手：</span>
            <span class="value">{{ orderInfo.rider.name }} ({{ orderInfo.rider.phone }})</span>
          </div>
        </div>
      </el-card>
      
      <el-card class="items-card">
        <div slot="header" class="items-header">
          <span>订单商品</span>
        </div>
        
        <div class="items-info">
          <el-table :data="orderItems" style="width: 100%">
            <el-table-column prop="productName" label="商品名称">
              <template slot-scope="scope">
                {{ scope.row.productName || scope.row.name || '未知商品' }}
              </template>
            </el-table-column>
            <el-table-column prop="price" label="单价" width="100">
              <template slot-scope="scope">
                ¥{{ (scope.row.price || 0).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="80">
              <template slot-scope="scope">
                {{ scope.row.quantity || 1 }}
              </template>
            </el-table-column>
            <el-table-column label="小计" width="120">
              <template slot-scope="scope">
                ¥{{ ((scope.row.price || 0) * (scope.row.quantity || 1)).toFixed(2) }}
              </template>
            </el-table-column>
          </el-table>
          
          <div class="order-total">
            <span>订单总计：</span>
            <span class="total-price">¥{{ (orderInfo.totalAmount || 0).toFixed(2) }}</span>
          </div>
        </div>
      </el-card>
      
      <div class="order-actions" v-if="orderInfo">
        <el-button type="primary" size="small" v-if="orderInfo.status === 3 && !orderInfo.isRated" @click="handleRateRider">
          评价骑手
        </el-button>
        <el-button type="danger" size="small" v-if="orderInfo.status === 0" @click="handleCancelOrder">
          取消订单
        </el-button>
        <el-button type="success" size="small" v-if="orderInfo.status === 1" @click="handleCheckOrderStatus">
          查看订单状态
        </el-button>
      </div>
      
      <!-- 骑手评价组件 -->
      <rider-rating 
        :visible.sync="ratingVisible"
        :order="orderInfo"
        :rider="riderInfo"
        @rating-success="handleRatingSuccess"
      />
    </div>
  </div>
</template>

<script>
import { getOrderDetail, cancelOrder } from '@/api/order'
import { getRiderDetail } from '@/api/rider'
import RiderRating from '@/components/RiderRating.vue'
import { mapState } from 'vuex'

export default {
  name: 'OrderDetail',
  components: {
    RiderRating
  },
  data() {
    return {
      orderInfo: null,
      loading: false,
      orderItems: [],
      riderInfo: null,
      ratingVisible: false
    }
  },
  computed: {
    ...mapState(['userInfo'])
  },
  created() {
    // 加载订单详情
    this.loadOrderDetail()
  },
  methods: {
    loadOrderDetail() {
      const orderId = this.$route.params.id
      if (!orderId) {
        this.$message.error('订单ID不能为空')
        this.$router.push('/order')
        return
      }

      // 检查登录状态
      if (!this.userInfo || !this.userInfo.id) {
        this.$message.warning('请先登录')
        this.$router.push('/login?redirect=' + this.$route.fullPath)
        return
      }

      this.loading = true

      // 调用API获取订单详情
      getOrderDetail(orderId)
        .then(res => {
          if (res.code === 200) {
            this.orderInfo = res.data

            // 处理items数据
            if (typeof this.orderInfo.items === 'string') {
              try {
                this.orderItems = JSON.parse(this.orderInfo.items) || []
              } catch (e) {
                console.error('解析订单商品失败', e)
                this.orderItems = []
              }
            } else if (Array.isArray(this.orderInfo.items)) {
              this.orderItems = this.orderInfo.items
            } else {
              this.orderItems = []
            }

            // 如果订单有骑手，获取骑手信息
            if (this.orderInfo.riderId) {
              this.fetchRiderInfo(this.orderInfo.riderId)
            }
          } else {
            this.$message.error(res.message || '获取订单详情失败')
            this.$router.push('/order')
          }
        })
        .catch(err => {
          console.error('获取订单详情失败', err)
          this.$message.error('获取订单详情失败')
          this.$router.push('/order')
        })
        .finally(() => {
          this.loading = false
        })
    },
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      return `${d.getFullYear()}-${d.getMonth()+1}-${d.getDate()} ${d.getHours()}:${d.getMinutes()}`
    },
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '待接单',
        2: '配送中',
        3: '已完成',
        4: '已取消'
      }
      return statusMap[status] || '未知状态'
    },
    getStatusType(status) {
      const typeMap = {
        0: 'info',
        1: 'warning',
        2: 'primary',
        3: 'success',
        4: 'danger'
      }
      return typeMap[status] || ''
    },
    cancelOrder() {
      this.$confirm('确定要取消该订单吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        // 调用API取消订单
        cancelOrder(this.orderInfo.id)
          .then(res => {
            if (res.code === 200) {
              this.orderInfo.status = 4 // 已取消
              this.$message.success('订单已取消')
            } else {
              this.$message.error(res.message || '取消订单失败')
            }
          })
          .catch(err => {
            console.error('取消订单失败', err)
            this.$message.error('取消订单失败')
          })
          .finally(() => {
            this.loading = false
          })
      }).catch(() => {})
    },
    fetchRiderInfo(riderId) {
      getRiderDetail(riderId)
        .then(res => {
          if (res.code === 200) {
            this.riderInfo = res.data
          }
        })
        .catch(err => {
          console.error('获取骑手信息失败', err)
        })
    },
    handleRateRider() {
      if (!this.riderInfo) {
        this.fetchRiderInfo(this.orderInfo.riderId)
      }
      this.ratingVisible = true
    },
    handleRatingSuccess() {
      this.loadOrderDetail()
      this.$message.success('感谢您的评价！')
    },
    handleCancelOrder() {
      this.cancelOrder()
    },
    handleCheckOrderStatus() {
      // 实现查看订单状态的逻辑
    }
  }
}
</script>

<style scoped>
.order-detail {
  padding: 20px;
}
.loading {
  padding: 20px;
}
.order-card, .merchant-card, .delivery-card, .items-card {
  margin-bottom: 20px;
}
.order-header, .merchant-header, .delivery-header, .items-header {
  display: flex;
  justify-content: space-between;
}
.info-item {
  margin-bottom: 10px;
}
.label {
  color: #666;
  display: inline-block;
  width: 100px;
}
.order-total {
  text-align: right;
  margin-top: 20px;
  font-size: 16px;
}
.total-price {
  font-size: 20px;
  color: #f56c6c;
  font-weight: bold;
}
.order-actions {
  text-align: center;
  margin-top: 30px;
}
</style> 